package com.more.offer.threadtest.unsafetest;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author pinoc
 * @date 2021/6/21
 * @description unsafe使用引导类加载器加载，而UnsafeTest 类是由系统类加载器加载，所以产生了权限错误。
 */
public class UnsafeTest {

	public static final Unsafe unsafe = Unsafe.getUnsafe();

	public static long varOffset;

	public volatile long var = 0;

	static{
		try {
			varOffset = unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("var"));
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		UnsafeTest unsafeTest = new UnsafeTest();
		boolean b = unsafe.compareAndSwapInt(unsafeTest, varOffset, 0, 1);
		System.out.println("result: " + b);
	}
}
